//
//  SHComposeViewController.swift
//  SHWeibo01
//
//  Created by 卫平玉 on 16/7/27.
//  Copyright © 2016年 卫平玉. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class SHComposeViewController: UIViewController {

    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    private func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
         setupNav()
        //添加控件
        view.addSubview(composeTextView)
       
        composeTextView.addSubview(composePictureView)
        
        view.addSubview(composeToolbarView)
        //添加约束
        composeTextView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        composePictureView.snp_makeConstraints { (make) -> Void in
            make.size.equalTo(CGSize(width:SCREENW - 20, height: SCREENW - 20))
            make.top.equalTo(composeTextView).offset(100)
            
            make.centerX.equalTo(composeTextView)
        }
        
        composeToolbarView.snp_makeConstraints { (make) -> Void in
            make.leading.bottom.trailing.equalTo(view)
            make.height.equalTo(44)
        }
       
        composeToolbarView.closure = {(type: SHComposeToolbarViewType)->() in
    
            switch type{
            case .Picture:
                print("图片")
                self.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("笑脸")
                self.switchKeyboard()
            case .Add:
                print("+")
                
            }
            
            }
        composePictureView.closure = {[weak self] in
            
            self?.selectImage()
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)

        // 表情键盘删除按钮通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDeleteButton", name: WBEmoticonDeleteButtonNoti, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtons:", name: WBEmoticonButtonsNoti, object: nil)
    }
    
    func emoticonButtons(noti: NSNotification){
        
        guard let emoticon = noti.object as? SHEmoticon else{
            return
        }
        
        if emoticon.isEmoji{
            
            let emoticonStr = (emoticon.code ?? "" as NSString).emoji()
            
            composeTextView.insertText(emoticonStr)
        }else{
            
            
            // 获取当前composeTextView 的富文本
            let allAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            let lineHeight = composeTextView.font!.lineHeight
            let attr = NSAttributedString(emoticon: emoticon, y: -4, lineHeight: lineHeight)

            
//            //文本附件
//            let att = NSTextAttachment()
//            
//            att.image = UIImage.getEmoticonImage(emoticon.path)
//             // 计算行高
//            let lineHeight = composeTextView.font!.lineHeight
//            // 记住一定要设置bounds
//            att.bounds = CGRectMake(0, -4, lineHeight, lineHeight)
//             // 不可变的富文本
//            let attr = NSAttributedString(attachment: att)
            // 获取当期选中的光标

            let selectedRange = composeTextView.selectedRange
            //插入不可变的富文本
            allAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            // 设置富文本属性
            allAttr.addAttributes([NSFontAttributeName:composeTextView.font!], range: NSRange(location: 0, length: allAttr.length))
            
            //赋值
            composeTextView.attributedText = allAttr
            // 重新设置composeTextView 选中光标
            composeTextView.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
            
            //发送一个通知，告诉textView隐藏占位符
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            composeTextView.delegate?.textViewDidChange!(composeTextView)
        }
    }
    
    //监听键盘的改变
    func keyboardWillChangeFrame(noti: NSNotification){
        
        guard let userInfo = noti.userInfo else{
            return
        }
        
        let duration = userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber
        
        let value = userInfo["UIKeyboardFrameEndUserInfoKey"] as!NSValue
        
        let rect = value.CGRectValue()
        
        self.composeToolbarView.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
        }
        
        //动画设置更新约束
        UIView.animateWithDuration(Double(duration)) { () -> Void in
            self.composeToolbarView.layoutIfNeeded()
        }
    }
    
    func emoticonDeleteButton(){
        
        composeTextView.deleteBackward()
    }
    
    private func setupNav(){
        
//        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Done, target: self, action: "cancelAction")
//        
//        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "确定", style: UIBarButtonItemStyle.Done, target: self, action: "sendAction")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", imgName: nil, target: self, action: "sendAction")
        navigationItem.rightBarButtonItem?.enabled = false
        //用来替代title
        navigationItem.titleView = titleView
    }
    
    //去掉private 要不然找不到这个方法
     func cancelAction(){
        
//   没有导航控制器？？     self.navigationController?.popViewControllerAnimated(true)
        
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func sendAction(){
        
        var allText = ""
        
        composeTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (result, range, _) -> Void in
            
            // 代表输入的是文本附件
            if let att = result["NSAttachment"] as? SHTextAttachment {
                
                allText += (att.emoticon?.chs ?? "")
            }else{
                
                // 文字
                // 字符串截取
                
                let str = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                allText += str
            }
        }

        composePictureView.imageList.count>0 ? update(allText) : upload(allText)
    }

    
    private lazy var titleView: UILabel = {
        let name = SHUserAccountViewModel.sharedTools.userAccount?.screen_name ?? ""
        
        let str = "发微博\n\(name)"
        let range = (str as NSString).rangeOfString(name)
        let attr = NSMutableAttributedString(string: str)
        
        attr.addAttributes([NSForegroundColorAttributeName:ThemeColor,NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)
        
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.attributedText = attr
        lab.textAlignment = .Center
        lab.sizeToFit()
        
        return lab
        
    }()
    
    private lazy var composeTextView: SHComposeTextView = {
        
        let view = SHComposeTextView()
        view.delegate = self
        view.font = UIFont.systemFontOfSize(15)
        view.placeholder = "上海微博三期了上海微博三期了上海微博三期了上海微博三期了上海微博三期了上海微博三期了"
        view.alwaysBounceVertical = true
        return view
    }()
    //配图
    private lazy var composePictureView: SHComposePictureView = SHComposePictureView()
    private lazy var composeToolbarView: SHComposeToolbarView = SHComposeToolbarView()

    private lazy var emoticonKeyboardView: SHEmoticonKeyboardView = SHEmoticonKeyboardView()
    //移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

// 底部视图按钮点击回调
extension SHComposeViewController{
    
    func selectImage(){
        
        let pickerVc = UIImagePickerController()
        
        pickerVc.delegate = self
        
        self.presentViewController(pickerVc, animated: true, completion: nil)
    }
    
    func switchKeyboard(){
        //代表是系统键盘
        if composeTextView.inputView == nil {
            
            composeTextView.inputView = emoticonKeyboardView
            composeToolbarView.isEmoticon = true
        }else{
            //反之代表是自定义键盘
            composeTextView.inputView = nil
            composeToolbarView.isEmoticon = false
        }
        
        // 刷新reloadInputViews
        composeTextView.reloadInputViews()
        
        //成为第一响应者
        composeTextView.becomeFirstResponder()
    }
}



//picker的代理方法
extension SHComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        composePictureView.addImages(image.getImageScale(600))
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

extension SHComposeViewController: UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        self.composeTextView.resignFirstResponder()
    }
}

// MARK: - 发送微博
extension SHComposeViewController{
    
    // 发送文字微博
    func update(status: String){
        
        SHNetworkTools.sharedTools.composeUpdate(status, success: { (response) -> () in
                SVProgressHUD.showSuccessWithStatus("发布成功")
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.25 * Double(NSEC_PER_SEC))),dispatch_get_main_queue()) { () -> Void in
                
              SVProgressHUD.dismiss()
            }
            
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("发布失败")
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.25 * Double(NSEC_PER_SEC))),dispatch_get_main_queue()) { () -> Void in
                    
                    SVProgressHUD.dismiss()
                }
        }
    }
    
    func upload(status: String){
        
        SHNetworkTools.sharedTools.composeUpload(status, imageList: composePictureView.imageList, success: { (response) -> () in
            SVProgressHUD.showSuccessWithStatus("发布成功")
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.25 * Double(NSEC_PER_SEC))),dispatch_get_main_queue()) { () -> Void in
                
                SVProgressHUD.dismiss()
            }
            }) { (error) -> () in
                SVProgressHUD.showErrorWithStatus("发布失败")
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.25 * Double(NSEC_PER_SEC))),dispatch_get_main_queue()) { () -> Void in
                    
                    SVProgressHUD.dismiss()
                }

        }
    }
}